<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>游戏大厅</title>
    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/game_hall.css">
    <script src="js/jquery.min.js"></script>
</head>
<body>
    <div class="nav">五子棋对战</div>
    <div class="container">

        <div >
            
            <div id="screen"></div>
            <div id="match-button">开始匹配</div>
        </div>
    </div>
    <script>
         
        $.ajax({
            url:"/userinfo",
            type:"get",
            success:function(data){
                let screenDiv = document.querySelector("#screen");
                screenDiv.innerHTML = '玩家: ' + data.username + ' 分数：' + data.score
                + "<br> 比赛场次：" + data.totalCount + "获胜场数：" + data.winCount; 
            },
            error:function(data){
                alert("获取用户信息失败");
            }
        });

        //此处进行初始化websocket，并且实现前端的匹配逻辑
        //此处路径必须写作 /findMatch，不能写成 /findMatch/
        let webSocketUrl = 'ws://' + location.host + '/findmatch';
        var websocket = new WebSocket(webSocketUrl);

        websocket.onopen = function(){
            console.log("onopen");
        }
        websocket.onclose = function(){
            console.log("onclose");
            
        }
        websocket.onerror = function(){
            console.log("onerror");
        }
        window.onbeforeunload = function(){
            websocket.close();
        }

        //处理服务器的响应
        websocket.onmessage = function(e){
            // 处理服务器返回的响应数据，针对’开始匹配‘或’结束匹配‘
            //解析得到的响应对象，返回的数据是一个JSON字符串，解析成js对象
            let resp = JSON.parse(e.data);
            let matchButton = document.querySelector("#match-button");
            if(!resp.ok){
                console.log("游戏大厅中接受到了失败响应! " + resp.reason);
                return;
            }
            if(resp.message == 'startMatch'){
                //开始匹配请求发送成功
                console.log("进入匹配队列成功");
                matchButton.innerHTML = '匹配中...(点击停止)';

            }else if(resp.message == 'stopMatch'){
                //结束匹配请求发送成功
                console.log('离开匹配队列成功');
                matchButton.innerHTML = '开始匹配';
            }else if(resp.message == 'matchSuccess'){
                console.log('匹配成功！进入游戏');
                location.replace("/game_room.html");
            }else if(resp.message == 'repeatConnection'){
                alert("检测到多开，使用其他账号登录");
                location.replace("/login.html");
            } else{
                console.log("收到了非法的响应!message=" + resp.message);
            }
        }

        //给匹配按钮添加一个点击事件
        let matchButton = document.querySelector("#match-button");
        matchButton.onclick = function(){
            // 触发websocket请求之前，先确认websocket连接是否正常
            if(websocket.readyState == websocket.OPEN){
                if(matchButton.innerHTML == '开始匹配'){
                    console.log('开始匹配');
                    websocket.send(JSON.stringify({
                        message:'startMatch',
                    }))
                }else if(matchButton.innerHTML == '匹配中...(点击停止)'){
                    console.log('停止匹配');
                    websocket.send(JSON.stringify({
                        message:'stopMatch',
                    }))
                }
            }else{
                // 连接当前是异常状态
                alert("当前连接已断开，请重新登录");
                location.replace("/login.html");
            }
        }
    </script>
</body>
</html>